// pages/home-page/add-customer/addCustomer.js
const app = getApp()
import util from '../../../utils/util'
const { validateAll } = require('../../../utils/validator.js')

Page({
  /**
   * 页面的初始数据
   */
  validator (rule, value, callback) {
    console.log(this)
    const reg = /^[0-9a-zA-Z]{4,20}$/
    if (value && !reg.test(value)) {
      callback(new Error('证件号码为4到20位数字和字母'))
    } else {
      callback()
    }
  },
  data: {
    info: {},
    customIndex: [0, 0,0,0],
    customArray: [],
    //当前选中数组
    onlyArray: [
      [],
      [],
      [],
      []
    ],
    customerId: '',
    rules: {
      realName: [
        { required: true, message: '姓名必填' },
        { validator(rule, value, callback) {
            const reg = /^[a-zA-Z\u4e00-\u9fa5]{2,10}$/
            if (!reg.test(value)) {
              callback(new Error('姓名需为2-10位中文或英文字符'))
            } else {
              callback()
            }
          } },
      ],
      phoneNum: [
        { required: true, message: '手机号码必填' },
        { validator(rule, value, callback) {
          const reg = /^[0-9]{11}$/
          if (value && !reg.test(value)) {
            callback(new Error('手机号码为11位数字'))
          } else {
            callback()
          }
        } }
      ],
      workNum: [
        { required: true, message: '工号必填' },
        { validator: (rule, value, callback) => {
          console.log(this)
          const reg = /^[0-9a-zA-Z]{2,20}$/
          if (value && !reg.test(value)) {
            callback(new Error('工号为2到20位数字和字母'))
          } else {
            callback()
          }
        } },
      ],
      orgId: [
        { required: true, message: '银行网点必选' },
      ],
    },
    loading: false
  },

  toUpdateFinancialManager() {
    const info = JSON.stringify(this.data.info)
    wx.navigateTo({
      url: `../add-financial-manager/addFinancialManager?info=${info}`,
    })
  },
  deleteFinancialManager () {
    let _this = this
    wx.showModal({
      title: '确定要删除吗？',
      cancelColor: '#666666',
      confirmColor: '#006DE7',
      success (res) {
        console.log(_this)
        if (res.confirm) {
          app.api.post({
            url: 'cpic_user_deleteStudent',
            data: {
              userId: _this.data.info.id
            }
          }).then(res => {
            wx.showToast({
              title: '删除成功',
              icon: 'success',
              duration: 2000
            })
            setTimeout(() => {
              wx.redirectTo({
                url: '/myself/pages/financial manager/financialManager',
              })
            }, 2000)
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const info = JSON.parse(options.info)
    this.setData({
      'info': info
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    app.api.post({
      url: 'cpic_user_getStudentUserById',
      data: { userId: this.data.info.id }
    }).then(res => {
      console.log(res)
      this.setData({
        'info': res
      })
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  inputInfo: function (e) {
    const { key } = e.currentTarget.dataset;
    const value = e.detail.value;
    this.setData({
      [`info.${key}`]: value
    })
    validateAll(key, this.data.rules[key], value)
  },

  
  getBankList: function () {
    var data = {
      customIndex: this.data.customIndex,
      onlyArray: this.data.onlyArray,
    };
    app.api.get({
      url: 'cpic_org_getAllOrgTree'
    }).then(res => {
      this.setData({
        'customArray': res.childs
      })
      for (var i = 0; i < res.childs.length; i++) {
        data.onlyArray[0].push(res.childs[i].orgName);
      }
      for (var j = 0; j <  res.childs[data.customIndex[0]].childs.length; j++) {
        data.onlyArray[1].push(res.childs[data.customIndex[0]].childs[j].orgName);
      }
      for (var p = 0; p <  res.childs[data.customIndex[0]].childs[data.customIndex[1]].childs.length; p++) {
        data.onlyArray[2].push(res.childs[data.customIndex[0]].childs[data.customIndex[1]].childs[p].orgName);
      }
      for (var k = 0; k <  res.childs[data.customIndex[0]].childs[data.customIndex[1]].childs[data.customIndex[2]].childs.length; k++) {
        data.onlyArray[3].push(res.childs[data.customIndex[0]].childs[data.customIndex[1]].childs[data.customIndex[2]].childs[k].orgName);
      }
      this.setData(data);
    })
  },
  //多列自定义选择器改变value的方法
  bindCustomPickerChange: function(e) {
    var customArray = this.data.customArray
    const id = customArray[e.detail.value[0]].childs[e.detail.value[1]].childs[e.detail.value[2]].childs[e.detail.value[3]].id
    this.setData({
      customIndex: e.detail.value,
      'info.orgId': id
    })
  },

  //多列自创选择器换列方法
  bindCustomPickerColumnChange: function(e) {
    var customArray = this.data.customArray,
      customIndex = this.data.customIndex,
      onlyArray = this.data.onlyArray;

    customIndex[e.detail.column] = e.detail.value;

    var searchColumn = () => {
      for (var i = 0; i < customArray.length; i++) {
        var arr1 = [];
        var arr2 = [];
        var arr3 = [];
        if (i == customIndex[0]) {
          for (var j = 0; j < customArray[i].childs.length; j++) {
            arr1.push(customArray[i].childs[j].orgName);
            if (j == customIndex[1]) {
              for (var k = 0; k < customArray[i].childs[j].childs.length; k++) {
                arr2.push(customArray[i].childs[j].childs[k].orgName);
                if (k == customIndex[2]) {
                  for (var p = 0; p < customArray[i].childs[j].childs[k].childs.length; p++) {
                    arr3.push(customArray[i].childs[j].childs[k].childs[p].orgName);
                  }
                  onlyArray[3] = arr3;
                }
              }
              onlyArray[2] = arr2;
            }
          }
          onlyArray[1] = arr1;
        }
      };
    }

    switch (e.detail.column) {
      case 0:
        customIndex[1] = 0;
        customIndex[2] = 0;
        customIndex[3] = 0;
        searchColumn();
        break;
      case 1:
        customIndex[2] = 0;
        customIndex[3] = 0;
        searchColumn();
        break;
      case 2:
        customIndex[3] = 0;
        searchColumn();
        break;  
    }
    this.setData({
      onlyArray: onlyArray,
      customIndex: customIndex
    });
  },
 
  submit: function () {
    const { info } = this.data
    let flag = true
    validateAll(this.data.rules, info, (valid) => {
      if (!valid) {
        flag = false
      }
    })

    if (flag) {
      this.setData({
        loading: true
      })
      app.api.post({
        url: 'cpic_user_createStudent',
        data: info
      }).then(res =>{
        wx.redirectTo({
          url: '../financial manager/financialManager'
        })
      }).finally(() => {
        this.setData({
          loading: false
        })
      })
    }
  },
  saveTag: function () {
    const { customerId } = this.data
    wx.navigateTo({
      url: `/pages/home-page/customer-analysis/customerAnalysis?id=${customerId}`
    })
  },
})